package com.flappySeeker.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.flappySeeker.common.BaseDaoImp;
import com.flappySeeker.model.TbUserinfo;
import com.flappySeeker.util.GetTools;
import com.flappySeeker.util.baidu.ZHutil;
import com.flappySeeker.util.emaydx.SingletonClient;

@Controller
@RequestMapping("/sms")
public class SMSAction {
	@Autowired
	private BaseDaoImp baseDaoImp;
	
	public BaseDaoImp getBaseDaoImp() {
		return baseDaoImp;
	}
	public void setBaseDaoImp(BaseDaoImp baseDaoImp) {
		this.baseDaoImp = baseDaoImp;
	}
	
	@RequestMapping(value="/smsverific",method=RequestMethod.POST)
	public void smsverific(TbUserinfo user,HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{
		boolean flag = false;//验证码状态，默认为不正确
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		Map<String,Object> list = baseDaoImp.sqlformap("select userid,username,usertel,verificode,vsmscode from tb_userinfo where username = '"+user.getUsername()+"' and usertel = '"+user.getUsertel()+"'");
		if(list!=null){
			if(list.get("vsmscode").toString().equals(user.getVsmscode())){
				baseDaoImp.update(
					"UPDATE tb_userinfo SET  effecttel = '1' WHERE userid = '"+list.get("userid").toString()+"'"
				);
				request.getSession().setAttribute("sf_userid", list.get("userid"));
				request.getSession().setAttribute("sf_username",list.get("username"));
				flag = true;
			}
		}
		out.print("[{'smsverific':'"+flag+"'}]");
		out.close();
	}
	
	
	@RequestMapping(value="/smssendmsg",method=RequestMethod.POST)
	public void SendSmsMsg(TbUserinfo user,HttpServletRequest request, HttpServletResponse response) throws IOException{
		int r=0;
		int rnum=0;
		rnum = GetTools.randomInt(6);
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String f = request.getParameter("flag");
		try {
			if(f!=null&&f!=""&&f.equals("s")){
				
			}else{
				f = "m";
			}
			Map<String,Object> list = baseDaoImp.sqlformap("select userid,username,usertel,verificode,vsmscode from tb_userinfo where username = '"+user.getUsername()+"' and usertel = '"+user.getUsertel()+"'");
			if(list==null){
				r = baseDaoImp.update(
						"INSERT INTO tb_userinfo " +
						"(userid,username,usersex,usertel,useremail,incity,inprovince,score,ispay,isclicked,resultsurl,verificode,vsmscode,createtime) VALUES " +
						"(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
						GetTools.GetGUID(),
						user.getUsername(),
						StringUtils.isEmpty(user.getUsersex())?"0":"1",
						StringUtils.isEmpty(user.getUsertel())?"":user.getUsertel(),
						StringUtils.isEmpty(user.getUseremail())?"":user.getUseremail(),
						StringUtils.isEmpty(user.getIncity())?"":user.getIncity(),
						StringUtils.isEmpty(user.getInprovince())?"":user.getInprovince(),
						user.getScore()==null?0:user.getScore(),
						user.getIspay()==null?0:user.getIspay(),
						user.getIsclicked()==null?0:user.getIsclicked(),
						StringUtils.isEmpty(user.getResultsurl())?"":user.getResultsurl(),
						StringUtils.isEmpty(user.getVerificode())?"":user.getVerificode(),
						rnum,
						GetTools.getNowDateTime()
					);
				if(r>0){
					int i=SingletonClient.getClient().sendSMS(new String[] {user.getUsertel()}, "【云平台中心】欢迎使用高考专业选评业务，请在页面输入六位验证码："+rnum+"，查看本次评测结果，如非本人操作，请不予理会。","",5);//带扩展码
					out.print("[{'suc':'"+i+"','userindb':'true','newuser':'true','sendsms':'true','haveverific':'false'}]");
				}
			}else{
				if(list.get("username").equals(user.getUsername())&&list.get("usertel").equals(user.getUsertel())){
					//用户存在系统，要求重新发送验证码
					r = baseDaoImp.update(
						"UPDATE tb_userinfo SET  vsmscode = '"+rnum+"' WHERE userid = '"+list.get("userid").toString()+"'"
					);
					if(r>0){
						int i=SingletonClient.getClient().sendSMS(new String[] {user.getUsertel()}, "【云平台中心】欢迎使用高考专业选评业务，请在页面输入六位验证码："+rnum+"，查看本次评测结果，如非本人操作，请不予理会。","",5);//带扩展码
						out.print("[{'suc':'"+i+"','userindb':'true','newuser':'false','sendsms':'true','haveverific':'false'}]");
					}
				}else{
					out.print("[{'suc':'1','userindb':'true','newuser':'false','sendsms':'true','haveverific':'false'}]");
				}/*else if(list.get(3).toString().equals(user.getVerificode())&&list.get(4).toString().equals("")){
					//用户存在系统，且序列号正确，则表示：当前用户没有发送验证短信或验证短信已验证过并清除，且序列号是购买未使用过的。
					out.print("{'userindb':'true','sendsms':'false','haveverific':'true','haveverificode':'true'}");
				}else if(!list.get(3).toString().equals(user.getVerificode())&&list.get(3).toString().equals("")&&list.get(4).toString().equals("")){
					//用户存在系统，且序列号不正确又为空，则表示：当前用户没有发送验证短信或验证短信已验证过并清除，且序列号没购买或序列号已经完成一次测试并使用清除了。
					out.print("{'userindb':'true','sendsms':'false','haveverific':'false','haveverificode':'false'}");
				}else if(!list.get(3).toString().equals(user.getVerificode())&&!list.get(3).toString().equals("")&&list.get(4).toString().equals("")){
					//用户存在系统，且序列号不正确又不为空，则表示：当前用户没有发送验证短信或验证短信已验证过并清除，且序列号不是自已购买的那个。
					out.print("{'userindb':'true','sendsms':'false','haveverific':'false','haveverificode':'true'}");
				}else{
					out.print("{'userindb':'true','sendsms':'false','haveverific':'false','haveverificode':'true'}");
				}*/
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.print("[{'suc':'1'}]");
		}
	}
	
	
	@RequestMapping(value="/getbaiduinfo")
	public void getBaiDuInfo(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
//		SELECT professionalname,content FROM  tb_professional WHERE content IS NULL 
		
//		try {
//			List<Map<String, Object>> list = baseDaoImp.sqllistmap("SELECT professionalname,content FROM  tb_professional WHERE content IS NULL  ");
//			for(int i = 0;i<=list.size();i++){
//				String ztext = ZHutil.getcontent(list.get(i).get("professionalname").toString());
//				try{
//					baseDaoImp.update(
//							"UPDATE tb_professional SET  content = '"+ztext+"' WHERE professionalname = '"+list.get(i).get("professionalname").toString()+"'"
//						);
//				}catch(Exception e){}
//				
//			}
//			
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		try {
			List<Map<String, Object>> list = baseDaoImp.sqllistmap("SELECT universityname FROM tb_university WHERE content = '' ");
			for(int i = 0;i<=list.size();i++){
				String ztext = ZHutil.getcontent(list.get(i).get("universityname").toString());
				try{
					baseDaoImp.update(
							"UPDATE tb_university SET  content = '"+ztext+"' WHERE universityname = '"+list.get(i).get("universityname").toString()+"'"
						);
				}catch(Exception e){}
				
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		String result = "http:\\/\\/baike.baidu.com\\/view\\/1563.htm";
		int beginIxR = result.lastIndexOf("\\/");
		String resultR = result.substring(beginIxR+2);
		System.out.println("结果：\n" + resultR);
		result = result.replaceAll("\\/", "/");
		System.out.println("结果：\n" + result);
		
	}
}
